package com.shu.es;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.UUID;

import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 删除特定的数据
 * @author Administrator
 *
 */
public class EsDataDelete {

	
	public static void main(String[] args) {
		//EsDataDelete.insertData("c27d7eab91a14ca2bc4ddfd334de81ff");
		EsDataDelete.insertData(UUID.randomUUID().toString());
		EsDataDelete.insertData(UUID.randomUUID().toString());
		EsDataDelete.insertData(UUID.randomUUID().toString());
		EsDataDelete.insertData(UUID.randomUUID().toString());
		EsDataDelete.insertData(UUID.randomUUID().toString());
		//EsDataDelete.deleateData2();
	}
	
	public static void insertData(String id) {
		RestHighLevelClient client = EsDataDelete.getClient();
		try {
			BulkRequest request = new BulkRequest();
			request.add(new IndexRequest("scale_hb20120101", "data", id)  
			        .source(XContentType.JSON,"cpu_temperature", "1"));
			BulkResponse bulkResponse = client.bulk(request);
			if(bulkResponse.hasFailures()) {
				System.out.println(bulkResponse.buildFailureMessage());
			}else {
				System.out.println("=========================================OK=========================================");
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(client!=null ) client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void deleateData2() {
		RestHighLevelClient client = EsDataDelete.getClient();
		try {
			BulkRequest request = new BulkRequest();
			request.add(new DeleteRequest("scale_hb20120101", "data", "89000210777346fc83d428743d9295ae")); 
			BulkResponse bulkResponse = client.bulk(request);
			if(bulkResponse.hasFailures()) {
				System.out.println(bulkResponse.buildFailureMessage());
			}else {
				System.out.println("=========================================OK=========================================");
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(client!=null ) client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	public static void deleateData() {
		RestHighLevelClient client = EsDataDelete.getClient();
		try {
			String index = "app_day2";
			BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
			//boolQuery.must(QueryBuilders.rangeQuery("create_time").gt(staTime).lt(endTime));
			boolQuery.must(QueryBuilders.termQuery("create_time", "20180110"));
			//boolQuery.should(QueryBuilders.matchQuery("", ""));
			SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
			searchSourceBuilder.query(boolQuery);
			String[] indes = {index};
			SearchRequest searchRequest = new SearchRequest(indes,searchSourceBuilder);
			searchSourceBuilder.from(0);
			searchSourceBuilder.size(10000);
			SearchResponse search = client.search(searchRequest);
			SearchHits hits = search.getHits();
			long totalHits = hits.getTotalHits();
			System.out.println("===================================Query result total: "+totalHits);
			ObjectMapper om = new ObjectMapper();
			int i=1;
			BulkRequest request = new BulkRequest();
			for(SearchHit hit : hits.getHits()) {
				String s = hit.getSourceAsString();
				String id = readJsonValue(om,s,"id");
				request.add(new DeleteRequest(index, "data", id)); 

				//DeleteRequest request = new DeleteRequest( index,"data",id);  
				//DeleteResponse deleteResponse = client.delete(request);
				System.out.println(totalHits+":"+i+":"+id);
				i++;
			}
			request.timeout(TimeValue.timeValueMinutes(2)); 
			request.timeout("10m"); 
			BulkResponse bulkResponse = client.bulk(request);
			if(bulkResponse.hasFailures()) {
				System.out.println(bulkResponse.buildFailureMessage());
			}else {
				System.out.println("=========================================OK=========================================");
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(client!=null ) client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private static String readJsonValue(ObjectMapper objectMapper, String jsonString,String key) {
		try {
			JsonNode root = objectMapper.readTree(jsonString);
		    Iterator<Entry<String, JsonNode>> elements = root.fields();
		      while (elements.hasNext()) {
		        Entry<String, JsonNode> node = elements.next();
		        if(key.equals(node.getKey())){
		        	return node.getValue().asText();
		        }
		      }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public static RestHighLevelClient getClient() {
		List<HttpHost> list = new ArrayList<HttpHost>();
		list.add(new HttpHost("192.168.1.18", 9200, "http"));
		HttpHost[] arr = new HttpHost[list.size()];
		arr = list.toArray(arr);
		RestClientBuilder builder = RestClient.builder(arr);
		
		return new RestHighLevelClient(builder);
	}
}
